#include "MC3172.h"
#include "printf.h"
#include "gpio.h"

//clockwise rotation
//    ----|        |--------|        |-------------------
//A       |        |        |        |
//        |--------|        |--------|
//     -------|        |--------|        |---------------
//B           |        |        |        |
//            |--------|        |--------|
//anti-clockwise rotation
//    --------|        |--------|        |---------------
//A           |        |        |        |
//            |--------|        |--------|
//     ---|        |--------|        |-------------------
//B       |        |        |        |
//        |--------|        |--------|

#define ROTARY_CLOCKWISE         1
#define ROTARY_ANTI_CLOCKWISE    2

#define ROTARY_A_PORT              GPIOC_BASE_ADDR
#define ROTARY_A_PIN               GPIO_PIN0
#define ROTARY_B_PORT              GPIOC_BASE_ADDR
#define ROTARY_B_PIN               GPIO_PIN1

void rotary_io_init(void)
{
#if(ROTARY_A_PORT == ROTARY_B_PORT)
    INTDEV_SET_CLK_RST(ROTARY_A_PORT, (INTDEV_RUN | INTDEV_IS_GROUP0 | INTDEV_CLK_IS_CORECLK_DIV2));
#else
    INTDEV_SET_CLK_RST(ROTARY_A_PORT, (INTDEV_RUN | INTDEV_IS_GROUP0 | INTDEV_CLK_IS_CORECLK_DIV2));
    INTDEV_SET_CLK_RST(ROTARY_B_PORT, (INTDEV_RUN | INTDEV_IS_GROUP0 | INTDEV_CLK_IS_CORECLK_DIV2));
#endif

    gpio_pin_mode(ROTARY_A_PORT, ROTARY_A_PIN, 0);
    gpio_pullup_set(ROTARY_A_PORT, ROTARY_A_PIN, 1);

    gpio_pin_mode(ROTARY_B_PORT, GPIO_PIN1, 0);
    gpio_pullup_set(ROTARY_B_PORT, GPIO_PIN1, 1);
}

u8 rotary_detect(u8 *dir)
{
    if(gpio_pin_level_get(ROTARY_A_PORT, ROTARY_A_PIN) == 0) {
        if(gpio_pin_level_get(ROTARY_B_PORT, ROTARY_B_PIN) == 0) {
            *dir = ROTARY_CLOCKWISE;
        } else {
            *dir = ROTARY_ANTI_CLOCKWISE;
        }
        return 1;
    }
    return 0;
}

void rotary_thread(void)
{
    u8 dir;
    printf_("This is rotary Test\n\r");

    rotary_io_init();
    while(1) {
        if(rotary_detect(&dir)) {
            if(dir == ROTARY_CLOCKWISE) {
                printf_("clockwise\n\r");
            } else {
                printf_("anti-clockwise\n\r");
            }
        }

        for (u32 var = 0; var < 500000; ++var) {
            NOP();
        }
    }
}
